﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using netDxf;
using netDxf.Entities;
using netDxf.Tables;
using Svg;
using Svg.Pathing;

namespace SvgToDxfConverter
{
    // 在SvgToDxfConverter命名空间内添加
    //public class TempTestRunner
    //{
    //    public static void Main(string[] args)
    //    {
    //        SvgToDxf svgToDxf = new SvgToDxf();
    //        svgToDxf.Convert("E:\\test.svg", "E:\\test.dxf");
    //    }
    //}
    public class SvgToDxf
    {
        public void Convert(string svgPath, string dxfPath)
        {
            // 加载 SVG 文件
            var svgDocument = SvgDocument.Open(svgPath);

            // 创建新的 DXF 文档
            var dxfDocument = new DxfDocument();
            float documentHeight  = svgDocument.Height.Value;
            // 转换 SVG 元素到 DXF 实体
            ConvertSvgElements(svgDocument.Children, dxfDocument, documentHeight);

            // 保存 DXF 文件
            dxfDocument.Save(dxfPath);

            Console.WriteLine($"转换完成: {svgPath} -> {dxfPath}");
        }

        private void ConvertSvgElements(SvgElementCollection svgElements, DxfDocument dxfDocument,float documentHeight)
        {
            
            // 处理所有 SVG 路径
            foreach (var element in svgElements)
            {
                if (element is SvgPath svgPath)
                {
                    //var dxfEntities = ConvertSvgPath(svgPath,documentHeight);
                    //foreach (var entity in dxfEntities)
                    //{
                    //    dxfDocument.Entities.Add(entity);
                    //}
                }
                else if (element is SvgRectangle svgRect)
                {
                    var dxfRect = ConvertSvgRectangle(svgRect, documentHeight);
                    dxfDocument.Entities.Add(dxfRect);
                }
                else if (element is SvgCircle svgCircle)
                {
                    var dxfCircle = ConvertSvgCircle(svgCircle, documentHeight);
                    dxfDocument.Entities.Add(dxfCircle);
                }
                else if (element is SvgLine svgLine)
                {
                    var dxfLine = ConvertSvgLine(svgLine, documentHeight);
                    dxfDocument.Entities.Add(dxfLine);
                }
                else if (element is SvgGroup svgGroup)
                {
                    ConvertSvgGroup(svgGroup, dxfDocument, documentHeight);

                }
                else if (element is SvgText svgText)
                {
                    var text = ConvertSvgText(svgText, documentHeight);
                    dxfDocument.Entities.Add(text);

                }
                else if (element is SvgPolygon svgPolygon)
                {
                    var poly = ConvertSvgPolygon(svgPolygon, documentHeight);
                   // dxfDocument.Entities.Add(poly);

                }
                else {

                    SvgElement element1 = element;
                    Console.WriteLine("Unsupported element type: " + element1.GetType().Name);
                }
                
            }
        }
          
        public void ConvertSvgGroup(SvgGroup svgGroup, DxfDocument dxfDocument, float documentHeight) {
            SvgElementCollection children = svgGroup.Children;
            List<SvgText> svgTexts= new List<SvgText>();
            List<SvgLine> svgLines = new List<SvgLine>();
            foreach (var element in children)
            {
                if (element is SvgText svgText)
                {
                    svgTexts.Add(svgText);
                }
                else if (element is SvgLine svgLine)
                {
                    svgLines.Add(svgLine);
                }
                else { 
                    //
                    ConvertSvgElements(element.Children, dxfDocument, documentHeight);
                    break;
                
                }
               
                
            }
            if (svgTexts.Count > 0 && svgLines.Count > 0)
            {
                //需要处理的文字
                List<SvgText> needHandledSvgText = svgTexts.Where(x => x.TextAnchor == SvgTextAnchor.Start || x.TextAnchor == SvgTextAnchor.End).ToList();
                float distant = 10;
                if (svgTexts.Count > 0)
                {
                    List<SvgLine> verticalLines = svgLines.Where(x => x.StartX == x.EndX).ToList();
                    //某个文字要选的是，x轴比自己小，但又距离自己最近的，startY比自己小，endY比自己大
                    List<IGrouping<float, SvgText>> list = svgTexts.GroupBy(x => x.Y[0].Value).OrderBy(group => group.Key).ToList();
                    if (list.Count > 1)
                    {
                        for (int i = 1; i < list.Count; i++)
                        {
                            foreach (var item in list[i])
                            {
                                if (item.TextAnchor != SvgTextAnchor.Start && item.TextAnchor != SvgTextAnchor.End)
                                {
                                    float value = item.X[0].Value;
                                    List<SvgLine> svgLines1 = verticalLines.Where(x => x.StartY < item.Y[0].Value && x.EndY > item.Y[0].Value).OrderBy(x => x.StartX).ToList();
                                    for (int j = 0; j < svgLines1.Count; j++)
                                    {
                                        if (svgLines1[i].StartX > value)
                                        {
                                            distant = value - svgLines1[i].StartX;
                                            break;
                                        }
                                    }

                                }
                            }

                        }


                    }


                    // 预先按X坐标排序文本和垂直线
                    var sortedTexts = needHandledSvgText.OrderBy(t => t.X[0].Value).ToList();
                    verticalLines = verticalLines.OrderBy(x => x.StartX.Value).ToList();

                    // 创建一个字典来存储结果
                    var textToNearestLeftLine = new Dictionary<SvgText, SvgLine>();

                    foreach (var text in sortedTexts)
                    {
                        float textX = text.X[0].Value;

                        // 找到所有在文本左侧的线
                        var leftLines = verticalLines.Where(line => line.StartX < textX);

                        if (leftLines.Any())
                        {
                            // 取最接近的那条线（StartX最大的）
                            var nearestLeftLine = leftLines.OrderByDescending(line => line.StartX.Value).First();
                            textToNearestLeftLine[text] = nearestLeftLine;
                        }
                        else
                        {
                            // 没有符合条件的线
                            textToNearestLeftLine[text] = null;
                        }
                    }

                    // 使用结果
                    foreach (var kvp in textToNearestLeftLine)
                    {
                        var text = kvp.Key;
                        var line = kvp.Value;
                        SvgUnitCollection svgUnitCollection = new SvgUnitCollection();
                        SvgUnit svgUnit = new SvgUnit(line.StartX + distant);
                        svgUnitCollection.Add(svgUnit);
                        text.X = svgUnitCollection;
                    }

                    ConvertSvgElements(children, dxfDocument, documentHeight);

                }

            }
            else {
                ConvertSvgElements(children, dxfDocument, documentHeight);
            }
            
           

          


        }
      
        private List<EntityObject> ConvertSvgPath(SvgPath svgPath, float documentHeight)
        {
            var entities = new List<EntityObject>();
            var pathSegments = svgPath.PathData;

            // 简化处理 - 实际实现需要解析所有路径命令
            // 这里只是一个基本示例
            foreach (var segment in pathSegments)
            {
                if (segment is SvgMoveToSegment moveTo)
                {
                    // 处理移动命令
                }
                else if (segment is SvgLineSegment line)
                {
                    var dxfLine = new Line(
                        new Vector2((double)line.Start.X, documentHeight-(double)line.Start.Y),
                        new Vector2((double)line.End.X, documentHeight - (double)line.End.Y));
                    entities.Add(dxfLine);
                }
                else if (segment is SvgCubicCurveSegment cubicCurve)
                {
                    
                }
                // 添加其他路径段类型的处理
            }

            return entities;
        }

        private List<Vector2> ApproximateBezierCurve(SvgPoint p0, SvgPoint p1, SvgPoint p2, SvgPoint p3)
        {
            var vertices = new List<Vector2>();
            int steps = 20; // 近似曲线的分段数

            for (int i = 0; i <= steps; i++)
            {
                double t = (double)i / steps;
                double x = Math.Pow(1 - t, 3) * p0.X +
                          3 * Math.Pow(1 - t, 2) * t * p1.X +
                          3 * (1 - t) * Math.Pow(t, 2) * p2.X +
                          Math.Pow(t, 3) * p3.X;
                double y = Math.Pow(1 - t, 3) * p0.Y +
                          3 * Math.Pow(1 - t, 2) * t * p1.Y +
                          3 * (1 - t) * Math.Pow(t, 2) * p2.Y +
                          Math.Pow(t, 3) * p3.Y;

                vertices.Add(new Vector2(x, y));
            }

            return vertices;
       
        }
        private EntityObject ConvertSvgPolygon(SvgPolygon svgPolygon, float documentHeight) { 
        return null;
        }

        private EntityObject ConvertSvgRectangle(SvgRectangle svgRect, float documentHeight)
        {
            var bottomLeft = new Vector2((double)svgRect.X, documentHeight-(double)svgRect.Y);
            var topRight = new Vector2((double)(svgRect.X + svgRect.Width), (double)(documentHeight-(svgRect.Y + svgRect.Height)));

            // 创建矩形作为多段线
            var vertices = new List<Vector2>
            {
                bottomLeft,
                new Vector2(topRight.X,bottomLeft.Y),
                topRight,
                new Vector2(bottomLeft.X,topRight.Y),
                bottomLeft // 闭合矩形
            };

            return new Polyline2D(vertices, true);
        }

        private EntityObject ConvertSvgCircle(SvgCircle svgCircle, float documentHeight)
        {
            var center = new Vector2((double)svgCircle.CenterX, documentHeight-(double)svgCircle.CenterY);
            return new Circle(center, (double)svgCircle.Radius);
        }

        private EntityObject ConvertSvgLine(SvgLine svgLine, float documentHeight)
        {
            var start = new Vector2((double)svgLine.StartX, documentHeight-(double)svgLine.StartY);
            var end = new Vector2((double)svgLine.EndX, documentHeight-(double)svgLine.EndY);
            return new Line(start, end);
        }

        private EntityObject ConvertSvgText(SvgText svgText, float documentHeight)
        {
            
            var text= new Text();
            text.Value = svgText.Text;

            // 添加字体样式配置
            var textStyle = new TextStyle("SimHei", "simhei.ttf"); // 使用黑体
            text.Style = textStyle;
            text.Position = new Vector3((double)svgText.X[0], documentHeight-(double)svgText.Y[0],0);
            text.Height= (double)svgText.FontSize;
            return text;
             
        }
       
       
    }
}